/**
 * 数据源表单组件
 * 用于创建和编辑数据源配置
 */

import React, { useEffect, useState, useCallback } from 'react';
import {
  Form,
  Input,
  Select,
  InputNumber,
  Switch,
  Button,
  Space,
  Tooltip,
  Alert,
  Divider
} from 'antd';
import {
  DatabaseOutlined,
  InfoCircleOutlined,
  ExperimentOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone
} from '@ant-design/icons';

import type {
  DataSource,
  DataSourceCreate,
  DataSourceUpdate,
  DatabaseType,
  ConnectionTestRequest,
  ConnectionTestResponse
} from '../types/datasource';
import {
  DatabaseTypeLabels,
  DatabaseDefaultPorts
} from '../types/datasource';
import { datasourceApi } from '../services/datasourceApi';

const { Option } = Select;
const { TextArea } = Input;

interface DataSourceFormProps {
  /** 编辑的数据源（为空时表示创建） */
  dataSource?: DataSource;
  /** 表单提交回调 */
  onSubmit: (values: DataSourceCreate | DataSourceUpdate) => Promise<void>;
  /** 取消回调 */
  onCancel: () => void;
  /** 是否正在提交 */
  loading?: boolean;
}

const DataSourceForm: React.FC<DataSourceFormProps> = ({
  dataSource,
  onSubmit,
  onCancel,
  loading = false
}) => {
  const [form] = Form.useForm();
  const [testLoading, setTestLoading] = useState(false);
  const [testResult, setTestResult] = useState<ConnectionTestResponse | null>(null);
  const [selectedType, setSelectedType] = useState<DatabaseType | undefined>(dataSource?.type);

  const isEditing = !!dataSource;

  // 初始化表单值
  useEffect(() => {
    if (dataSource) {
      form.setFieldsValue({
        name: dataSource.name,
        display_name: dataSource.display_name,
        description: dataSource.description,
        type: dataSource.type,
        host: dataSource.host,
        port: dataSource.port,
        database_name: dataSource.database_name,
        username: dataSource.username,
        connection_params: dataSource.connection_params,
        is_active: dataSource.is_active,
        connection_timeout: dataSource.connection_timeout,
        max_connections: dataSource.max_connections
      });
      setSelectedType(dataSource.type);
    } else {
      // 新建时的默认值
      form.setFieldsValue({
        is_active: true,
        connection_timeout: 30,
        max_connections: 10
      });
    }
  }, [dataSource, form]);

  // 数据库类型变化时更新默认端口
  const handleTypeChange = useCallback((type: DatabaseType) => {
    setSelectedType(type);
    const defaultPort = DatabaseDefaultPorts[type];
    form.setFieldValue('port', defaultPort);
    setTestResult(null); // 清除之前的测试结果
  }, [form]);

  // 测试连接
  const handleTestConnection = useCallback(async () => {
    try {
      // 验证必填字段
      await form.validateFields(['type', 'host', 'port', 'database_name', 'username', 'password']);
      
      const values = form.getFieldsValue();
      const testRequest: ConnectionTestRequest = {
        type: values.type,
        host: values.host,
        port: values.port,
        database_name: values.database_name,
        username: values.username,
        password: values.password,
        connection_params: values.connection_params,
        connection_timeout: values.connection_timeout || 30
      };

      setTestLoading(true);
      setTestResult(null);

      const result = await datasourceApi.testConnectionParams(testRequest);
      setTestResult(result);

    } catch (error: any) {
      if (error.errorFields) {
        // 表单验证错误
        return;
      }
      // API错误已在service中处理
      setTestResult({
        success: false,
        message: '连接测试失败',
        error_details: { error_message: error.message || '未知错误' }
      });
    } finally {
      setTestLoading(false);
    }
  }, [form]);

  // 表单提交
  const handleSubmit = useCallback(async () => {
    try {
      const values = await form.validateFields();
      await onSubmit(values);
    } catch (error) {
      // 表单验证错误，不需要处理
    }
  }, [form, onSubmit]);

  // 表单验证规则
  const formRules = {
    name: [
      { required: true, message: '请输入数据源名称' },
      { min: 1, max: 100, message: '数据源名称长度为1-100个字符' },
      {
        pattern: /^[a-zA-Z0-9_-]+$/,
        message: '数据源名称只能包含字母、数字、下划线和连字符'
      }
    ],
    display_name: [
      { required: true, message: '请输入显示名称' },
      { min: 1, max: 100, message: '显示名称长度为1-100个字符' }
    ],
    type: [
      { required: true, message: '请选择数据库类型' }
    ],
    host: [
      { required: true, message: '请输入主机地址' },
      { min: 1, max: 255, message: '主机地址长度为1-255个字符' }
    ],
    port: [
      { required: true, message: '请输入端口号' },
      { type: 'number', min: 1, max: 65535, message: '端口号范围为1-65535' }
    ],
    database_name: [
      { required: true, message: '请输入数据库名称' },
      { min: 1, max: 100, message: '数据库名称长度为1-100个字符' }
    ],
    username: [
      { required: true, message: '请输入用户名' },
      { min: 1, max: 100, message: '用户名长度为1-100个字符' }
    ],
    password: [
      { required: !isEditing, message: '请输入密码' },
      { min: 1, max: 255, message: '密码长度为1-255个字符' }
    ],
    connection_timeout: [
      { type: 'number', min: 5, max: 300, message: '连接超时时间范围为5-300秒' }
    ],
    max_connections: [
      { type: 'number', min: 1, max: 100, message: '最大连接数范围为1-100' }
    ]
  };

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      initialValues={{
        is_active: true,
        connection_timeout: 30,
        max_connections: 10
      }}
    >
      {/* 基本信息 */}
      <div style={{ marginBottom: 16 }}>
        <h4 style={{ margin: '0 0 16px 0', color: '#1890ff' }}>
          <DatabaseOutlined style={{ marginRight: 8 }} />
          基本信息
        </h4>
        
        <Form.Item
          name="name"
          label="数据源名称"
          rules={formRules.name}
          tooltip="唯一标识，用于系统内部引用"
        >
          <Input
            placeholder="请输入数据源名称（英文标识）"
            disabled={isEditing}
          />
        </Form.Item>

        <Form.Item
          name="display_name"
          label="显示名称"
          rules={formRules.display_name}
        >
          <Input placeholder="请输入显示名称（中文名称）" />
        </Form.Item>

        <Form.Item
          name="description"
          label="描述"
        >
          <TextArea
            placeholder="请输入数据源描述（可选）"
            rows={3}
            maxLength={1000}
            showCount
          />
        </Form.Item>

        <Form.Item
          name="is_active"
          label="启用状态"
          valuePropName="checked"
        >
          <Switch
            checkedChildren="启用"
            unCheckedChildren="禁用"
          />
        </Form.Item>
      </div>

      <Divider />

      {/* 连接配置 */}
      <div style={{ marginBottom: 16 }}>
        <h4 style={{ margin: '0 0 16px 0', color: '#1890ff' }}>
          <DatabaseOutlined style={{ marginRight: 8 }} />
          连接配置
        </h4>

        <Form.Item
          name="type"
          label="数据库类型"
          rules={formRules.type}
        >
          <Select
            placeholder="请选择数据库类型"
            onChange={handleTypeChange}
            disabled={isEditing}
          >
            {Object.entries(DatabaseTypeLabels).map(([value, label]) => (
              <Option key={value} value={value}>
                {label}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="host"
          label="主机地址"
          rules={formRules.host}
        >
          <Input placeholder="请输入主机地址或IP" />
        </Form.Item>

        <Form.Item
          name="port"
          label="端口号"
          rules={formRules.port}
        >
          <InputNumber
            placeholder="请输入端口号"
            style={{ width: '100%' }}
            min={1}
            max={65535}
          />
        </Form.Item>

        <Form.Item
          name="database_name"
          label="数据库名称"
          rules={formRules.database_name}
        >
          <Input placeholder="请输入数据库名称" />
        </Form.Item>

        <Form.Item
          name="username"
          label="用户名"
          rules={formRules.username}
        >
          <Input placeholder="请输入数据库用户名" />
        </Form.Item>

        <Form.Item
          name="password"
          label={isEditing ? "密码（留空表示不修改）" : "密码"}
          rules={formRules.password}
        >
          <Input.Password
            placeholder={isEditing ? "留空表示不修改密码" : "请输入数据库密码"}
            iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
          />
        </Form.Item>
      </div>

      <Divider />

      {/* 高级配置 */}
      <div style={{ marginBottom: 16 }}>
        <h4 style={{ margin: '0 0 16px 0', color: '#1890ff' }}>
          <InfoCircleOutlined style={{ marginRight: 8 }} />
          高级配置
        </h4>

        <Form.Item
          name="connection_timeout"
          label="连接超时时间（秒）"
          rules={formRules.connection_timeout}
        >
          <InputNumber
            placeholder="连接超时时间"
            style={{ width: '100%' }}
            min={5}
            max={300}
          />
        </Form.Item>

        <Form.Item
          name="max_connections"
          label="最大连接数"
          rules={formRules.max_connections}
        >
          <InputNumber
            placeholder="最大连接数"
            style={{ width: '100%' }}
            min={1}
            max={100}
          />
        </Form.Item>
      </div>

      {/* 连接测试结果 */}
      {testResult && (
        <div style={{ marginBottom: 16 }}>
          <Alert
            type={testResult.success ? 'success' : 'error'}
            message={testResult.message}
            description={
              testResult.success ? (
                <div>
                  {testResult.response_time && (
                    <div>响应时间: {testResult.response_time}ms</div>
                  )}
                  {testResult.database_info && (
                    <div>
                      数据库版本: {testResult.database_info.version}
                    </div>
                  )}
                </div>
              ) : (
                testResult.error_details?.error_message
              )
            }
            showIcon
            closable
            onClose={() => setTestResult(null)}
          />
        </div>
      )}

      {/* 操作按钮 */}
      <Form.Item style={{ marginBottom: 0 }}>
        <Space>
          <Button
            type="primary"
            htmlType="submit"
            loading={loading}
          >
            {isEditing ? '更新' : '创建'}
          </Button>
          
          <Button
            icon={<ExperimentOutlined />}
            onClick={handleTestConnection}
            loading={testLoading}
            disabled={loading}
          >
            测试连接
          </Button>
          
          <Button onClick={onCancel} disabled={loading}>
            取消
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default DataSourceForm;
